package com.lixh.roommanager

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.github.salomonbrys.kotson.fromJson
import com.google.gson.Gson
import com.lixh.roommanager.ui.Constant
import com.lixh.roommanager.ui.LOG
import com.lixh.roommanager.ui.YMD
import com.lixh.roommanager.ui.bean.Room
import com.lixh.roommanager.ui.main.SectionsPagerAdapter
import com.lixh.roommanager.ui.plusDays
import com.lixh.roommanager.ui.utils.UStore
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    private var roomData by UStore(Constant.JSON_ROOM, "[]")

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val sectionsPagerAdapter = SectionsPagerAdapter(this, supportFragmentManager)
        view_pager.adapter = sectionsPagerAdapter
        tabs.setupWithViewPager(view_pager)

    }

    fun switchTab(position: Int) {
        view_pager.currentItem = position
    }

    override fun onResume() {
        super.onResume()
        "activity Resume".LOG
        val rooms =
            Gson().fromJson<List<Room>>(roomData)
        if (rooms.isNotEmpty()) {
            checkRoom(rooms)
        }
    }

    private fun checkRoom(rooms: List<Room>) {
        //今日时间
        val cTime: Long = System.currentTimeMillis()
        val today: String = cTime.YMD
        //过滤 1 空闲 2 有人
        rooms.map {
            val state = it.state
            //有人的 检测最后时间
            if (it.endTime > 0 && (state == 2 || state == 3 || state == 4)) {
                val endTime = it.endTime.YMD
                //时间相同 今日房间是最后一天
                when {
                    endTime == today -> {
                        it.state = 3
                    }
                    endTime.plusDays(1) == today -> {
                        //房子退房
                        it.state = 4
                    }
                    endTime.plusDays(2) == today -> {
                        //归入到闲置
                        it.state = 1
                        it.endTime = 0
                        it.startTime = 0
                    }
                }

            }
        }
        //保存新的数据
        roomData = Gson().toJson(rooms)
    }
}
